import router from './core/router'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {Message} from 'element-ui'
import {Route} from 'vue-router'
import {UserModule} from '@/core/store/modules/user'
import i18n from '@/assets/language' // Internationalization
import settings from './core/config/settings'
import {getToken} from "@/core/utils/storage";

NProgress.configure({showSpinner: false});

const whiteList = ['/login'];

const getPageTitle = (key: string) => {
    const hasKey = i18n.te(`route.${key}`);
    if (hasKey) {
        const pageName = i18n.t(`route.${key}`);
        return `${pageName} - ${settings.title}`
    }
    return `${settings.title}`
};

router.beforeEach(async (to: Route, _: Route, next: any) => {
    NProgress.start();

    // Determine whether the user has logged in
    if (getToken()) {
        if (to.path === '/login') {
            // If is logged in, redirect to the home page
            next({path: '/'});
            NProgress.done()
        } else {
            if (UserModule.roles.length === 0) {
                try {
                    await UserModule.GetUserInfo();
                    // const roles = UserModule.roles;
                    // PermissionModule.GenerateRoutes(roles);
                    next({...to, replace: true})
                } catch (err) {
                    // Remove token and redirect to login page
                    UserModule.ResetToken();
                    Message.error(err || 'Has Error');
                    next(`/login?redirect=${to.path}`);
                    NProgress.done()
                }
            } else {
                next()
            }
        }
    } else {
        // Has no token
        if (whiteList.indexOf(to.path) !== -1) {
            // In the free login whitelist, go directly
            next()
        } else {
            // Other pages that do not have permission to access are redirected to the login page.
            next(`/login?redirect=${to.path}`);
            NProgress.done()
        }
    }
});

router.afterEach((to: Route) => {
    NProgress.done();
    document.title = getPageTitle(to.meta.title)
});
